<template>
  <el-dialog
      v-model="dialogVisible"
      :title="isMultiple ? '批量编辑文章' : '编辑文章'"
      width="1200px"
      style="height: auto"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClose"
  >
    <div v-loading="loading || translationStore.loading">
      <!-- 单篇文章编辑 -->
      <template v-if="!isMultiple">
        <el-form :model="form" label-width="200px">
          <!-- 语言选择 -->
<!--          <el-form-item label="目标语言">-->
<!--            <el-select v-model="form.targetLanguage" placeholder="请选择目标语言" clearable filterable>-->
<!--              <el-option-->
<!--                  v-for="(lang, code) in supportedLanguages"-->
<!--                  :key="code"-->
<!--                  :label="`${lang.nativeName} (${lang.name})`"-->
<!--                  :value="code"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->

          <el-form-item label="原标题">
            <el-input type="textarea" :rows="2" v-model="form.originalTitle" disabled />
          </el-form-item>

          <el-form-item :label="`${form.targetLanguage ? getLanguageName(form.targetLanguage) : '编辑后'} 标题`">
            <el-input v-model="form.title" />
            <template v-if="form.targetLanguage">
              <el-button
                  type="primary"
                  link
                  @click="handleTranslate('title')"
                  :loading="translating.title"
              >
                翻译标题
              </el-button>
            </template>
          </el-form-item>

          <el-form-item label="原描述">
            <el-input
                v-model="form.originalDescription"
                type="textarea"
                :rows="3"
                disabled
            />
          </el-form-item>

          <el-form-item :label="`${form.targetLanguage ? getLanguageName(form.targetLanguage) : '编辑后'} 描述`">
            <el-input
                v-model="form.description"
                type="textarea"
                :rows="4"
            />
            <template v-if="form.targetLanguage">
              <el-button
                  type="primary"
                  link
                  @click="handleTranslate('description')"
                  :loading="translating.description"
              >
                翻译描述
              </el-button>
            </template>
          </el-form-item>
        </el-form>
      </template>

      <!-- 批量编辑预览 -->
      <template v-else>
        <div class="batch-preview">
          <p>已选择 {{ articles.length }} 篇文章</p>

          <!-- 批量编辑模式选择 -->
          <el-radio-group v-model="batchEditMode" class="mb-4">
            <el-radio label="manual">手动批量编辑</el-radio>
<!--            <el-radio label="translate">批量翻译</el-radio>-->
          </el-radio-group>

          <!-- 翻译模式 -->
          <template v-if="batchEditMode === 'translate'">
            <el-form-item label="目标语言">
              <el-select v-model="form.targetLanguage" placeholder="请选择目标语言">
                <el-option
                    v-for="(lang, code) in supportedLanguages"
                    :key="code"
                    :label="`${lang.nativeName} (${lang.name})`"
                    :value="code"
                />
              </el-select>
            </el-form-item>

            <el-table :data="articles" height="300">
              <el-table-column prop="title" label="原标题" width="200" show-overflow-tooltip />
              <el-table-column
                  prop="description"
                  label="原描述"
                  show-overflow-tooltip
              />
            </el-table>
          </template>

          <!-- 手动编辑模式 -->
          <template v-else>
            <el-table :data="articles" width="800px">
              <el-table-column label="标题" width="300">
                <template #default="{ row }">
                  <el-input type="textarea" :rows="2" v-model="row.title" />
                </template>
              </el-table-column>
              <el-table-column label="描述">
                <template #default="{ row }">
                  <el-input
                      v-model="row.description"
                      type="textarea"
                      :rows="2"
                  />
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </template>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            @click="handleConfirm"
            :loading="saving"
        >
          {{ getConfirmButtonText() }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useArticleStore } from '@/stores/article'
import { useTranslationStore } from '@/stores/translation'

const props = defineProps({
  visible: Boolean,
  articles: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'save'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const isMultiple = computed(() => props.articles.length > 1)

const articleStore = useArticleStore()
const translationStore = useTranslationStore()

const loading = ref(false)
const saving = ref(false)
const translating = reactive({
  title: false,
  description: false
})

const supportedLanguages = ref({})
const batchEditMode = ref('manual') // 'translate' 或 'manual'

// 表单数据
const form = ref({
  articleId: '',
  originalTitle: '',
  originalDescription: '',
  title: '',
  description: '',
  targetLanguage: ''
})

// 获取按钮文本
const getConfirmButtonText = () => {
  if (!isMultiple.value) {
    return form.value.targetLanguage ? '翻译并保存' : '保存'
  } else {
    return batchEditMode.value === 'translate' ? '批量翻译' : '批量保存'
  }
}

// 获取支持的语言列表
const loadSupportedLanguages = async () => {
  try {
    const languages = await translationStore.fetchSupportedLanguages()
    supportedLanguages.value = languages.data
  } catch (error) {
    // 错误已在store中处理
  }
}

// 获取语言名称
const getLanguageName = (code) => {
  return supportedLanguages.value[code]?.nativeName || code
}

// 检查文章是否有特定语言的翻译
const hasTranslation = (article, language) => {
  // 首先检查 article.translations 是否存在
  if (!article.translations) return false

  // 然后检查是否有匹配的语言
  return article.translations.some(t => t.language === language)
}

const selected = async (article) => {
  // 获取文章现有翻译
  try {
    const response = await translationStore.getArticleTranslations(article.id)
    if (response && response.data && response.data.length > 0) {
      // 将翻译数据附加到文章对象
      article.translations = response.data
    }
  } catch (error) {
    console.error('Failed to fetch translations', error)
  }
}

// 初始化表单数据
const initForm = async () => {
  if (!isMultiple.value && props.articles.length === 1) {
    const article = props.articles[0]
    form.value = {
      articleId: article.id,
      originalTitle: article.title,
      originalDescription: article.description || '',
      title: '',
      description: '',
      targetLanguage: ''
    }

    // 初始化编辑状态
    props.articles.forEach(article => {
      article.editedTitle = ''
      article.editedDescription = ''
    })

    // // 获取文章现有翻译
    // try {
    //   const response = await translationStore.getArticleTranslations(article.id)
    //   if (response && response.data && response.data.length > 0) {
    //     // 将翻译数据附加到文章对象
    //     article.translations = response.data
    //   }
    // } catch (error) {
    //   console.error('Failed to fetch translations', error)
    // }
  }
}

// 处理翻译
const handleTranslate = async (field) => {
  if (!form.value.targetLanguage) {
    ElMessage.warning('请选择目标语言')
    return
  }

  translating[field] = true
  try {
    let textToTranslate = field === 'title' ? form.value.originalTitle : form.value.originalDescription

    const response = await translationStore.translateText(textToTranslate, form.value.targetLanguage)
    form.value[field] = response.data.translatedText

    ElMessage.success(`${field === 'title' ? '标题' : '描述'}翻译完成`)
  } catch (error) {
    // 错误已在store中处理
  } finally {
    translating[field] = false
  }
}

// 批量翻译
const handleBatchTranslate = async () => {
  if (!form.value.targetLanguage) {
    ElMessage.warning('请选择目标语言')
    return
  }

  loading.value = true
  try {
    const articleIds = props.articles.map(article => article.id)
    const response = await translationStore.batchTranslateArticles(articleIds, form.value.targetLanguage, true)

    ElMessage.success(`批量翻译完成，成功${response.data.successCount}篇，失败${response.data.failCount}篇`)
    emit('save', response.data.results)
    handleClose()
  } catch (error) {
    // 错误已在store中处理
  } finally {
    loading.value = false
  }
}

// 批量手动保存
const handleBatchManualSave = async () => {
  const articlesToSave = props.articles
      .filter(a => a.title || a.description)
      .map(a => ({
        id: a.id,
        title: a.title || undefined,
        description: a.description || undefined
      }))

  if (articlesToSave.length === 0) {
    ElMessage.warning('没有修改任何内容')
    return
  }

  loading.value = true
  try {
    const response = await articleStore.batchSaveArticles(articlesToSave)
    emit('save', response.data.results)
    handleClose()
  } catch (error) {
    // 错误已在store中处理
  } finally {
    loading.value = false
  }
}

// 保存单篇文章
const handleSaveSingle = async () => {
  if (!form.value.title && !form.value.description) {
    ElMessage.warning('请输入要保存的内容')
    return
  }

  saving.value = true
  try {
    await articleStore.saveArticle({
      id: form.value.articleId,
      title: form.value.title,
      description: form.value.description,
      targetLanguage: form.value.targetLanguage
    })
    emit('save')
    handleClose()
  } catch (error) {
    // 错误已在store中处理
  } finally {
    saving.value = false
  }
}

// 保存修改
const handleConfirm = async () => {
  if (isMultiple.value) {
    if (batchEditMode.value === 'translate') {
      ElMessage.error('谷歌翻译配额不足')
      // await handleBatchTranslate()
    } else {
      await handleBatchManualSave()
    }
  } else {
    await handleSaveSingle()
  }
}

const handleClose = () => {
  form.value = {
    articleId: '',
    originalTitle: '',
    originalDescription: '',
    title: '',
    description: '',
    targetLanguage: ''
  }
  batchEditMode.value = 'manual'
  dialogVisible.value = false
}

// 监听弹窗显示
watch(() => dialogVisible.value, (val) => {
  if (val) {
    initForm()
  }
})

onMounted(() => {
  loadSupportedLanguages()
})
</script>

<style scoped>
/* 主对话框样式 */
.el-dialog__wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 更好地控制表单布局 */
.el-form {
  width: 100%;
}

/* 语言选择控件宽度限制 */
.el-form-item__content .el-select {
  width: 300px !important;
}

/* 批量预览区域样式 */
.batch-preview {
  width: 100%;
}

/* 单篇文章编辑表单样式 */
.el-form-item.is-required .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

/* 操作按钮样式 */
.translate-action {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

/* 批量编辑模式选择样式 */
.batch-mode-selector {
  margin-bottom: 20px;
  padding: 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

/* 表格样式优化 */
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .el-form-item__content .el-select {
    width: 100% !important;
  }
}

/* 翻译状态标签样式 */
.translation-status {
  display: inline-flex;
  align-items: center;
}

.translation-status .el-icon {
  margin-right: 4px;
}

/* 表单项内的操作按钮容器 */
.form-actions {
  display: flex;
  margin-top: 8px;
}

/* 加载状态遮罩调整 */
.el-loading-mask {
  z-index: 2000;
}

.batch-preview {
  margin: 20px 0;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>